package hkust.lingx.csit5110.android.lib.server;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import android.os.Handler;

/**
 * main server,only accept client connection then create ServerHandlerThread to
 * process message(call Handler) Don't reply the client here, that's the
 * FeedBackClient's job. so it's a simple twisted p2p CS chat model When receive
 * message,NumbServer is the server When send message,FeedBackClient is the
 * client
 * 
 * @author lingx825
 * 
 */
public class NumbServer implements Runnable {
  private ArrayList<Handler> handlerList;
  private ServerSocket serverSocket;
  private int port;

  public NumbServer(int port) {
    this.port = port;
    handlerList = new ArrayList<Handler>();
  }

  @Override
  public void run() {
    try {
      serverSocket = new ServerSocket(port);
    } catch (Exception e) {
      e.printStackTrace();
    }
    while (true) {
      try {
        Socket clientSocket = serverSocket.accept();
        Thread t = new Thread(new ServerHandlerThread(this, clientSocket));
        t.start();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

  }

  /**
   * Implement your Handler what to do when receive a AnchorMessage
   * 
   * @param handler
   */
  public void registerHandler(Handler handler) {
    handlerList.add(handler);
  }

  public ArrayList<Handler> getHandlerList() {
    return handlerList;
  }

  public void setHandlerList(ArrayList<Handler> handlerList) {
    this.handlerList = handlerList;
  }

}
